package java_test.reflection;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class ReflectonTest1 {
    public static void main(String[] args) throws NoSuchFieldException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        testConstructor();
    }

    public static void testField() throws NoSuchFieldException, InstantiationException, IllegalAccessException {
//        Class<Person1> clazz = Person1.class;
//        Person1 person1 = clazz.newInstance();
//        Field id = clazz.getField("id");
//        id.set(person1, 1001);
//        //System.out.println(person1.id);
//
//        System.out.println(id.get(person1));

        Class<Person1> clazz = Person1.class;
        Person1 person1 = clazz.newInstance();
        Field name = clazz.getDeclaredField("name");
        name.setAccessible(true);
        name.set(person1, "胡宇婷");
        System.out.println(name.get(person1));
    }

    public static void testMethod() throws InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        Class<Person1> clazz = Person1.class;
        Person1 person1 = clazz.newInstance();
        Method show = clazz.getDeclaredMethod("show", String.class);
        show.setAccessible(true);
        Object chn = show.invoke(person1, "CHN");
        System.out.println(chn);
        System.out.println("************************");
        Method showDesc = clazz.getDeclaredMethod("showDesc");
        showDesc.setAccessible(true);
        //Object invoke = showDesc.invoke(Person1.class);
        Object invoke = showDesc.invoke(null);
        System.out.println(invoke);
    }

    public static void testConstructor() throws InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        Class<Person1> clazz = Person1.class;
        Constructor declaredConstructor = clazz.getDeclaredConstructor(String.class);
        declaredConstructor.setAccessible(true);
        Object tom = declaredConstructor.newInstance("Tom");
        System.out.println(tom);
    }
}
